<template>
  <div class="chat-area" :class="chatAreaClasses">
    <!-- 消息列表区域 -->
    <div class="message-section">
      <MessageList
        :messages="chatStore.messages"
        :is-streaming="chatStore.isStreaming"
        :streaming-message-id="streamingMessageId"
        @message-action="handleMessageAction"
        @retry-message="handleRetryMessage"
      />
    </div>
    
    <!-- 输入区域 -->
    <div class="input-section">
      <QuestionInput
        v-model="chatStore.currentInput"
        :disabled="!chatStore.canSend"
        :loading="chatStore.isStreaming"
        :placeholder="inputPlaceholder"
        @submit="handleSubmit"
        @voice-input="handleVoiceInput"
      />
    </div>
    
    <!-- 快速操作栏 -->
    <div v-if="showQuickActions" class="quick-actions">
      <el-button
        v-for="action in quickActions"
        :key="action.key"
        type="text"
        :icon="action.icon"
        @click="handleQuickAction(action.key)"
        class="quick-action-btn"
      >
        {{ action.label }}
      </el-button>
    </div>
    
    <!-- 连接状态提示 -->
    <transition name="slide-up">
      <div v-if="!chatStore.isConnected" class="connection-alert">
        <el-alert
          title="连接已断开"
          description="正在尝试重新连接..."
          type="warning"
          :closable="false"
          show-icon
        />
      </div>
    </transition>
    
    <!-- 输入提示 -->
    <transition name="fade">
      <div v-if="showInputHints && !chatStore.hasMessages" class="input-hints">
        <div class="hints-container">
          <h3 class="hints-title">试试这些问题：</h3>
          <div class="hints-list">
            <div
              v-for="hint in inputHints"
              :key="hint"
              class="hint-item"
              @click="applyHint(hint)"
            >
              <el-icon><ChatDotRound /></el-icon>
              <span>{{ hint }}</span>
            </div>
          </div>
        </div>
      </div>
    </transition>
  </div>
</template>

<script setup lang="ts">
import { useChatStore } from '@/stores/chat'
import { useUIStore } from '@/stores/ui'
import { useTaskStore } from '@/stores/task'
import MessageList from './MessageList.vue'
import QuestionInput from './QuestionInput.vue'

const chatStore = useChatStore()
const uiStore = useUIStore()
const taskStore = useTaskStore()

// Props
interface Props {
  sessionId?: string
  autoScroll?: boolean
  showTimestamp?: boolean
  showQuickActions?: boolean
  showInputHints?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  autoScroll: true,
  showTimestamp: true,
  showQuickActions: true,
  showInputHints: true
})

// Emits
interface Emits {
  messageSubmit: [message: string]
  taskConfirm: [taskIds: string[]]
  taskModify: [modification: any]
}

const emit = defineEmits<Emits>()

// 状态
const streamingMessageId = ref<string | null>(null)
const isVoiceInputActive = ref(false)

// 计算属性
const chatAreaClasses = computed(() => ({
  'chat-area': true,
  'chat-area--empty': !chatStore.hasMessages,
  'chat-area--streaming': chatStore.isStreaming,
  'chat-area--disconnected': !chatStore.isConnected
}))

const inputPlaceholder = computed(() => {
  if (!chatStore.isConnected) return '连接中...'
  if (chatStore.isStreaming) return 'AI正在回复中...'
  if (taskStore.isExecuting) return '任务执行中...'
  return '输入您的问题...'
})

// 快速操作配置
const quickActions = [
  { key: 'clear', label: '清空对话', icon: 'Delete' },
  { key: 'export', label: '导出对话', icon: 'Download' },
  { key: 'regenerate', label: '重新生成', icon: 'RefreshRight' },
  { key: 'stop', label: '停止生成', icon: 'VideoPause' }
]

// 输入提示
const inputHints = [
  '帮我分析这份销售数据的趋势',
  '写一份关于人工智能的技术报告',
  '设计一个用户登录流程',
  '解释一下机器学习的基本概念',
  '制定一个项目管理计划',
  '优化这段代码的性能'
]

// 方法
const handleSubmit = async (message: string) => {
  try {
    await chatStore.sendMessage(message)
    emit('messageSubmit', message)
  } catch (error) {
    console.error('Failed to send message:', error)
    uiStore.showError('发送消息失败，请重试')
  }
}

const handleMessageAction = (action: string, messageId: string) => {
  switch (action) {
    case 'copy':
      copyMessage(messageId)
      break
    case 'delete':
      deleteMessage(messageId)
      break
    case 'retry':
      handleRetryMessage(messageId)
      break
    case 'edit':
      editMessage(messageId)
      break
  }
}

const handleRetryMessage = async (messageId: string) => {
  try {
    await chatStore.retryMessage(messageId)
  } catch (error) {
    console.error('Failed to retry message:', error)
    uiStore.showError('重试消息失败')
  }
}

const handleVoiceInput = (isActive: boolean) => {
  isVoiceInputActive.value = isActive
  // 这里可以集成语音识别功能
}

const handleQuickAction = async (actionKey: string) => {
  switch (actionKey) {
    case 'clear':
      await clearChat()
      break
    case 'export':
      await exportChat()
      break
    case 'regenerate':
      await regenerateLastResponse()
      break
    case 'stop':
      await stopGeneration()
      break
  }
}

const copyMessage = async (messageId: string) => {
  const success = await chatStore.copyMessage(messageId)
  if (success) {
    uiStore.showSuccess('消息已复制到剪贴板')
  } else {
    uiStore.showError('复制失败')
  }
}

const deleteMessage = (messageId: string) => {
  ElMessageBox.confirm(
    '确定要删除这条消息吗？',
    '确认删除',
    {
      confirmButtonText: '删除',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    chatStore.deleteMessage(messageId)
    uiStore.showSuccess('消息已删除')
  }).catch(() => {
    // 用户取消
  })
}

const editMessage = (messageId: string) => {
  // 实现消息编辑功能
  console.log('Edit message:', messageId)
}

const clearChat = async () => {
  try {
    const result = await ElMessageBox.confirm(
      '确定要清空当前对话吗？此操作不可撤销。',
      '确认清空',
      {
        confirmButtonText: '清空',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    if (result === 'confirm') {
      chatStore.clearMessages()
      uiStore.showSuccess('对话已清空')
    }
  } catch {
    // 用户取消
  }
}

const exportChat = async () => {
  try {
    if (!chatStore.currentSessionId) {
      uiStore.showError('没有可导出的对话')
      return
    }
    
    const sessionData = chatStore.exportSession(chatStore.currentSessionId)
    if (sessionData) {
      const blob = new Blob([JSON.stringify(sessionData, null, 2)], {
        type: 'application/json'
      })
      
      const url = URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = `chat-session-${sessionData.id}.json`
      document.body.appendChild(a)
      a.click()
      document.body.removeChild(a)
      URL.revokeObjectURL(url)
      
      uiStore.showSuccess('对话已导出')
    }
  } catch (error) {
    console.error('Export failed:', error)
    uiStore.showError('导出失败')
  }
}

const regenerateLastResponse = async () => {
  try {
    await chatStore.regenerateResponse()
  } catch (error) {
    console.error('Failed to regenerate response:', error)
    uiStore.showError('重新生成失败')
  }
}

const stopGeneration = async () => {
  try {
    // 停止当前生成
    if (chatStore.isStreaming) {
      chatStore.disconnectSSE()
      uiStore.showSuccess('已停止生成')
    }
  } catch (error) {
    console.error('Failed to stop generation:', error)
    uiStore.showError('停止失败')
  }
}

const applyHint = (hint: string) => {
  chatStore.currentInput = hint
  // 自动聚焦到输入框
  nextTick(() => {
    const inputElement = document.querySelector('.question-input textarea') as HTMLTextAreaElement
    if (inputElement) {
      inputElement.focus()
    }
  })
}

// 监听连接状态变化
watch(() => chatStore.isConnected, (connected) => {
  if (connected) {
    uiStore.showSuccess('连接已恢复')
  }
})

// 监听流式消息变化
watch(() => chatStore.isStreaming, (streaming) => {
  if (streaming) {
    // 开始流式传输时的处理
    streamingMessageId.value = chatStore.messages[chatStore.messages.length - 1]?.id || null
  } else {
    // 流式传输结束时的处理
    streamingMessageId.value = null
  }
})

// 生命周期
onMounted(() => {
  // 如果指定了sessionId，切换到该会话
  if (props.sessionId && props.sessionId !== chatStore.currentSessionId) {
    chatStore.switchToSession(props.sessionId)
  }
  
  // 如果没有当前会话，创建新会话
  if (!chatStore.currentSessionId) {
    chatStore.createSession()
  }
})

// 监听路由参数变化
watch(() => $route.params.sessionId, (newSessionId) => {
  if (newSessionId && typeof newSessionId === 'string') {
    chatStore.switchToSession(newSessionId)
  }
})
</script>

<style lang="scss" scoped>
.chat-area {
  display: flex;
  flex-direction: column;
  height: 100%;
  position: relative;
  background: var(--bg-color);
  
  &.chat-area--empty {
    .message-section {
      @include flex-center;
    }
  }
  
  &.chat-area--streaming {
    .input-section {
      pointer-events: none;
      opacity: 0.8;
    }
  }
  
  &.chat-area--disconnected {
    .input-section {
      pointer-events: none;
      opacity: 0.6;
    }
  }
}

// 消息列表区域
.message-section {
  flex: 1;
  overflow: hidden;
  position: relative;
}

// 输入区域
.input-section {
  flex-shrink: 0;
  padding: var(--spacing-md);
  border-top: 1px solid var(--border-color);
  background: var(--bg-color);
}

// 快速操作栏
.quick-actions {
  @include flex-center;
  gap: var(--spacing-sm);
  padding: var(--spacing-sm) var(--spacing-md);
  border-top: 1px solid var(--border-color);
  background: var(--bg-color-light);
  
  .quick-action-btn {
    font-size: var(--font-size-small);
    
    &:hover {
      color: var(--primary-color);
    }
  }
}

// 连接状态提示
.connection-alert {
  position: absolute;
  top: var(--spacing-md);
  left: var(--spacing-md);
  right: var(--spacing-md);
  z-index: var(--z-index-top);
}

// 输入提示
.input-hints {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  @include flex-center;
  background: var(--bg-color);
  z-index: var(--z-index-normal);
}

.hints-container {
  text-align: center;
  max-width: 600px;
  padding: var(--spacing-xl);
}

.hints-title {
  font-size: var(--font-size-large);
  color: var(--text-color-primary);
  margin-bottom: var(--spacing-lg);
}

.hints-list {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: var(--spacing-md);
}

.hint-item {
  @include flex-start;
  gap: var(--spacing-sm);
  padding: var(--spacing-md);
  border: 1px solid var(--border-color);
  border-radius: var(--border-radius-base);
  cursor: pointer;
  transition: var(--transition-base);
  
  &:hover {
    border-color: var(--primary-color);
    background: var(--primary-color-lighter);
    transform: translateY(-2px);
    box-shadow: var(--box-shadow-base);
  }
  
  .el-icon {
    color: var(--primary-color);
    font-size: 18px;
  }
  
  span {
    color: var(--text-color-regular);
    font-size: var(--font-size-small);
  }
}

// 过渡动画
.slide-up-enter-active,
.slide-up-leave-active {
  transition: all 0.3s ease;
}

.slide-up-enter-from,
.slide-up-leave-to {
  opacity: 0;
  transform: translateY(-20px);
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

// 响应式适配
@include respond-to(md) {
  .input-section {
    padding: var(--spacing-sm);
  }
  
  .quick-actions {
    padding: var(--spacing-xs) var(--spacing-sm);
    gap: var(--spacing-xs);
  }
  
  .hints-list {
    grid-template-columns: 1fr;
  }
  
  .hint-item {
    padding: var(--spacing-sm);
  }
}
</style>